<!-- 联盟组织 -->
<template>
  <div>
    <div class="p-4 pb-0 text-xl"
      >本联盟已有<span class="text-color-[#2878ff]">{{ total }}</span
      >个组织</div
    >
    <BasicTable row-key="id" @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="openSelectModal">添加组织</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'merchantName'">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <Image
              :src="record.logoUrl"
              width="24px"
              height="24px"
              style="object-fit: cover;"
              ></Image>
            </div>
            <div class="pl-2">{{ record.merchantName }}</div>
          </div>
        </template>
        <template v-else-if="column.key === 'joinFlag'">
          <Switch
            v-model:checked="record.joinFlag"
            :checkedValue="IsOnStateEnum.ON"
            :unCheckedValue="IsOnStateEnum.OFF"
            @change="hangeStatus(record)"
          />
        </template>

        <template v-else-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '设置',
                onClick: () => openSetModal(record),
              },
            ]"
          ></TableAction>
        </template>
      </template>
    </BasicTable>

    <OrganizationSet @register="registerOrganizationSet" />
    <SelectOrganization @register="registerOrganization" @ok="configSelect" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema } from '@/components/Table';
  import { reactive, ref } from 'vue';
  import OrganizationSet from '../components/organizationSet.vue';
  import { useModal } from '@/components/Modal';
  import {
    getMerchantList,
    merchanConfigInfo,
    merchantUpStatus,
    addMerchant,
  } from '@/api/hby/resourceLeague/index';
  import SelectOrganization from '../components/selectOrganization.vue';
  import { Switch, Image, Modal } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
import { MerchanItem } from '@/api/hby/resourceLeague/type';
import { IsOnStateEnum } from '@/enums/customFormEnum';
import { MerchantListType } from '@/enums/resourceLeague';


  const tableSchemas = reactive<FormSchema[]>([
    {
      field: `keyWord`,
      label: `关键词`,
      component: 'Input',
      componentProps: {
        placeholder: '输入组织名称',
      },
      colProps: {
        span: 6,
      },
    },
    {
      field: `[startTime, endTime]`,
      label: `加入时间`,
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        placeholder: ['开始时间', '结束时间'],
      },
      colProps: {
        span: 8,
      },
    },
  ]);

  const total = ref(0);
  const [registerTable, { reload, clearSelectedRowKeys, getRawDataSource }] = useTable({
    api: (params: any) => {
      clearSelectedRowKeys();
      return getMerchantList(params);
    },
    columns: [
      {
        title: '组织信息',
        dataIndex: 'merchantName',
        width: 272,
        align: 'center',
      },
      {
        title: '参与联盟业务',
        dataIndex: 'joinFlag',
        width: 100,
        align: 'center',
      },
      {
        title: '推入联盟产品(个)',
        dataIndex: 'productNum',
        width: 150,
        align: 'center',
      },
      {
        title: '联盟帮售订单(个)',
        dataIndex: 'salesNum',
        width: 150,
        align: 'center',
      },
      {
        title: '已推广订单(个)',
        dataIndex: 'distributionNum',
        width: 150,
        align: 'center',
      },
      {
        title: '加入时间',
        dataIndex: 'joinDate',
        width: 200,
        align: 'center',
      },
    ],
    useSearchForm: true,
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    formConfig: {
      labelWidth: 100,
      schemas: tableSchemas as unknown as FormSchema[],
    },
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    afterFetch: (data: MerchanItem[]) => {
      total.value = getRawDataSource().total;
      return data;
    },
  });
  // 打开设置组织配置弹窗
  const [registerOrganizationSet, { openModal: openRegisterOrganizationSet }] = useModal();
  const openSetModal = (row: MerchanItem) => {
    merchanConfigInfo(row.id).then((res) => {
      openRegisterOrganizationSet(true, res);
    });
  };



  // 打开选择组织弹窗
  const [registerOrganization, { openModal: openRegisterOrganization }] = useModal();
  const openSelectModal = () => {
    openRegisterOrganization(true, {
      type: MerchantListType.PRODUCTAUDIT,
      disabledIds: []
    });
  };
  const { createMessage } = useMessage();
  // 添加组织
  const configSelect = (selectedList) => {
    const merchants = selectedList.map((v) => v.id);
    addMerchant(merchants).then(() => {
      createMessage.success('添加组织成功');
      reload();
    });
  };


  // 切换加入联盟状态
  const hangeStatus = (row) => {
      Modal.confirm({
      title: row.joinFlag ? '开启参与联盟业务权限' : '关闭参与联盟业务权限',
      content: row.joinFlag ? `确定要开启“${row.merchantName}”参与联盟业务的权限？开启本权限后，该组织可申请联盟推广产品、分销联盟产品。` : `确定要关闭“${row.merchantName}”参与联盟业务的权限？关闭本权限后，该组织将不可申请联盟推广产品、不可分销联盟产品。已经分销的产品链接将全部失效，在开启权限后恢复。`,
      cancelText: row.joinFlag ? '暂不开启' : '暂不关闭',
      okText: row.joinFlag ? '开启权限' : '关闭权限',
      onOk: async () => {
        return new Promise<void>((resolve, reject) => {
          merchantUpStatus({ id: row.id, joinFlag: row.joinFlag }).then(() => {
            createMessage.success('状态更改成功');
            resolve();
          }).catch((err)=>{
            createMessage.error('状态更改失败');
            row.joinFlag = row.joinFlag ? IsOnStateEnum.OFF : IsOnStateEnum.ON;
            reject(err);
          });
        });
      },
      onCancel: () => {
        row.joinFlag = row.joinFlag ? IsOnStateEnum.OFF : IsOnStateEnum.ON;
      }
    });
  };
</script>

<style lang="less" scoped></style>
